import re
import string
from datetime import datetime, timedelta
from random import choice

from django.core.mail import send_mail
from django.db import models
from rest_framework import serializers
from users.models import EmailVerifyCode, UserProfile


class VerifyCodeSerializer(serializers.Serializer):
    email = serializers.EmailField()

    def validate_email(self, email):
        # 验证邮箱是否已注册
        if UserProfile.objects.filter(email=email).count():
            raise serializers.ValidationError("邮箱已注册")

        # 验证码发送频率限制
        one_min_ago = datetime.now() - timedelta(hours=0,minutes=1,seconds=0)
        if EmailVerifyCode.objects.filter(add_time__gt=one_min_ago, email=email):
            raise serializers.ValidationError("距上次发送验证码不足1分钟")

        return email
